Arithmetic and Logical Operators

The main factor that led to the invention of Computers was the search to simplify Mathematical Operations. Every computer language provides extensive support for wide range of arithmetic operations. Python’s arithmetic operators are superset of those in C.

Let’s have look at some of operations…

Arithmetic Operators

In [21]:
4 + 3
Out[21]:
7
In [32]:
'hi' + ' ' + 'how are you'
Out[32]:
'hi how are you'
In [37]:
'c' + 1
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-37-4e0a1d805b35> in <module>()
----> 1 'c' + 1

TypeError: Can't convert 'int' object to str implicitly

In C, char is equivalent to uint8 and arithmetic operations can be done. In Python, it’s not the case. Thus trying to do so raises a TypeError

In [22]:
4 - 3
Out[22]:
1
In [23]:
4 / 3
Out[23]:
1.3333333333333333

Note

Division results in floating point number, unlike C. This behaviour is default from Python 3. Earlier version behaved in the same way as C. Use // operator to perform floor division.

In [24]:
4 // 3
Out[24]:
1
In [27]:
5.9 // 3.0
Out[27]:
1.0

// operator results in integer division, it rounds down the result to nearest integer

In [34]:
4 * 5
Out[34]:
20
In [4]:
'he' * 2 + 'h'  # A string expression!
Out[4]:
'heheh'
In [28]:
4 ** 3
Out[28]:
64
In [2]:
4 ** 0.5
Out[2]:
2.0

** operator is Power operator. a**b gives a raised to the power b

In [3]:
5 % 4
Out[3]:
1

All other arithmetic operators and bitwise operators and comparison operators that are present in C are supported. But the Logical Operators differs from C.

Logical Operators - and, or and not

Before starting with Logical Operators, note that True and False are boolean primitives in Python as opposed to true and false in C++,Java and C#


Note

  • In Python, Single line comments start with #
  • Multiline comments start and end with triple quotes, i.e., '''

Example

# This is a single line comment
'''This is
  a multi-
  line comment'''
In [43]:
# Initialize 2 integer variables
a = 20
b = 10
In [44]:
a == 20 and b == 10
Out[44]:
True
In [45]:
a is 20 or b is 0
Out[45]:
True
In [46]:
not a == 20
Out[46]:
False